package com.eversec.util.command;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

import sun.misc.BASE64Decoder;


public class StringUtil {
	
	private static final String CHARSET = "UTF-8";
	
	/**
	 * 判断str是否经过Base64编码
	 * @param str 字符串
	 * @return 是、否
	 */
	public static boolean isBase64(String str) {
		boolean flag = false;
		try {
			String tem = getBaseByString(getStringByBaseString(str));
			if (tem.equals(str)) {
				flag = true;
			}
		} catch (Exception e) {
			flag = false;
		}
		return flag;
	}
	
	/**
	 * 给字符串填充到指定长度
	 * 
	 * @param str
	 *            字符串
	 * @param length
	 *            指定的长度
	 * @param flag
	 *            TRUE前部填充
	 * @return 填充后的字符串
	 */
	public static String fillString(String str, int length, boolean flag) {
		if (str == null) {
			return "";
		}
		if (str.length() < length) {
			for (int i = str.length(); i < length; i++) {
				if (flag) {
					str = "0" + str;
				} else {
					str += "0";
				}
			}
		}
		return str;
	}
	
	/**
	 * 将字符串转为字符数组
	 * 
	 * @param str
	 *            字符串
	 * @return 字符数组
	 */
	public static byte[] getByte(String str) {
		byte[] bArray = null;
		try {
			bArray = str.getBytes(CHARSET);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return bArray;
	}
	
	public static byte[] getByte(String str, String charSet) {
		byte[] bArray = null;
		try {
			bArray = str.getBytes(charSet);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return bArray;
	}
	
	public static String getString(byte[] bArray, String charSet) {
		String string = null;
		try {
			string = new String(bArray, charSet);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return string;
	}
	
	/**
	 * 字节数组转换为流inputstream 
	 */
	public static final InputStream byte2Input(byte[] buf) {  
	    return new ByteArrayInputStream(buf);  
	}  
	  
	/**
	 * 流inputstream转换为字节数组 
	 */
    public static final byte[] input2byte(InputStream inStream)  
            throws IOException {  
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();  
        byte[] buff = new byte[100];  
        int rc = 0;  
        while ((rc = inStream.read(buff, 0, 100)) > 0) {  
            swapStream.write(buff, 0, rc);  
        }  
        byte[] in2b = swapStream.toByteArray();  
        return in2b;  
    }  
	
	/**
	 * 将字符串base64后转字符串
	 * 
	 * @param bArray
	 *            字符数组
	 * @return 字符转
	 */
	public static String getBaseByString(String str) {
		String result = "";
//		byte[] bArray = getByte(str);
		byte[] bArray = getByte(str, Constant.CHARACTER_SET);
		bArray = Base64.encodeBase64(bArray);
//		String result = new String(bArray);
		try {
			result = new String(bArray, Constant.CHARACTER_SET);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * 将字符串base64
	 * 
	 * @param bArray
	 *            字符数组
	 * @return 字符转
	 */
	public static byte[] getBase64(String str) {
		byte[] bArray = getByte(str);
		bArray = Base64.encodeBase64(bArray);
		return bArray;
	}
	
	
	public static String getBaseByString(String str, String charSet) {
		byte[] bArray = getByte(str, charSet);
		bArray = Base64.encodeBase64(bArray);
		try {
			str = new String(bArray, charSet);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return str;
	}
	
	/**
	 * 将字符数组base64后转字符串
	 * 
	 * @param bArray
	 *            字符数组
	 * @return 字符转
	 */
	public static String getBaseByByte(byte[] bArray) {
		String str = null;
		bArray = Base64.encodeBase64(bArray);
		try {
			str = new String(bArray,Constant.CHARACTER_SET);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return str;
		
//		String returnStr = null;
//		try {
//			returnStr = new BASE64Encoder().encode(bArray);
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		return returnStr;
	}
	
	public static String getStringByString(String str) {
		String returnStr = null;
		try {
			byte[] strByte = getByteByBaseString(str);
			returnStr = new String(strByte, Constant.CHARACTER_SET);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return returnStr;
	}
	
	/**
	 * 将字符串转为字符数组并解base64
	 * 
	 * @param str
	 *            字符串
	 * @return 字符数组
	 */
	public static byte[] getByteByBaseString(String str) {
		byte[] bArray = null;
		try {
			bArray = str.getBytes(Constant.CHARACTER_SET);
			if (Base64.isArrayByteBase64(bArray)) {
				bArray = Base64.decodeBase64(bArray);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
//		try {
//			bArray = new BASE64Decoder().decodeBuffer(str);
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		return bArray;
	}
	
	/**
	 * MD5的算法在RFC1321 中定义 在RFC 1321中，给出了Test suite用来检验你的实现是否正确： MD5 ("") =
	 * d41d8cd98f00b204e9800998ecf8427e MD5 ("a") = 0cc175b9c0f1b6a831c399e269772661
	 * MD5 ("abc") = 900150983cd24fb0d6963f7d28e17f72 MD5 ("message digest") =
	 * f96b697d7cb7938d525a2f31aaf161d0 MD5 ("abcdefghijklmnopqrstuvwxyz") =
	 * c3fcd3d76192e4007dfb496cca67e13b
	 * @author haogj
	 * 传入参数：一个字节数组 传出参数：字节数组的 MD5 结果字符串
	 */
	public static String getMD5(byte[] source) {
		String s = null;
		char hexDigits[] = { // 用来将字节转换成 16 进制表示的字符
		'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
				'e', 'f' };
		try {
			java.security.MessageDigest md = java.security.MessageDigest
					.getInstance("MD5");
			md.update(source);
			byte tmp[] = md.digest(); // MD5 的计算结果是一个 128 位的长整数，
			// 用字节表示就是 16 个字节
			char str[] = new char[16 * 2]; // 每个字节用 16 进制表示的话，使用两个字符，
			// 所以表示成 16 进制需要 32 个字符
			int k = 0; // 表示转换结果中对应的字符位置
			for (int i = 0; i < 16; i++) { // 从第一个字节开始，对 MD5 的每一个字节
				// 转换成 16 进制字符的转换
				byte byte0 = tmp[i]; // 取第 i 个字节
				str[k++] = hexDigits[byte0 >>> 4 & 0xf]; // 取字节中高 4 位的数字转换,
				// >>> 为逻辑右移，将符号位一起右移
				str[k++] = hexDigits[byte0 & 0xf]; // 取字节中低 4 位的数字转换
			}
			s = new String(str); // 换后的结果转换为字符串

		} catch (Exception e) {
			e.printStackTrace();
		}
		return s;
	}
	
	/**
	 * SHA-1加密 
	 */
	public static String SHAEncrypt(byte[] bt) {
		MessageDigest md = null;
		String strDes = null;
		
//		byte[] bt = strSrc.getBytes();
		try {
			md = MessageDigest.getInstance("SHA-1");
			md.update(bt);
            strDes = bytes2Hex(md.digest());  //to HexString
		}
		catch (NoSuchAlgorithmException e) {
			return null;
		}
        return strDes;
	}

	public static String bytes2Hex(byte[] bts) {
		String des="";
		String tmp=null;
		for (int i=0; i<bts.length; i++) {
           tmp=(Integer.toHexString(bts[i] & 0xFF));
           if (tmp.length() == 1) {
               des += "0";
           }
           des += tmp;
        }
        return des;
	}

	
	/**
     * 对数据用AES算法加密
     * @param plainText  要加密的字节数组
     * @param key  密钥
     * @return 加密后的字节数组
     */
    public static byte [] encrypt(byte [] plainText, byte [] key) {
        try{
        SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] decryptText = cipher.doFinal(plainText);
        return decryptText;
         } catch(Exception e) {
             e.printStackTrace();
             return null;
         }
    }
    
    /**
     * 对数据用AES算法加密,将加密的结果，转换为16进制
     * @param plainText  要加密的字节数组
     * @param key  密钥
     * @return 加密后的字节数组
     */
    public static String encryptHex(byte [] plainText, byte [] key) {
        try{
        SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] decryptText = cipher.doFinal(plainText);
        return parseByte2HexStr(decryptText);
         } catch(Exception e) {
             e.printStackTrace();
             return null;
         }
    }
    
    public static byte[] aes(byte[] plainText, String aeskey, String aesOffsets) {
    	 try{
    		if(aeskey.length() > 16){
        		byte[] aesBytes = parseHexStr2Byte(aeskey);
        		aeskey = new String(aesBytes, Constant.CHARACTER_SET);
        		System.out.println("aeskey转换后的偏移量：" + aeskey);
        	}
 	        SecretKeySpec skeySpec = new SecretKeySpec(aeskey.getBytes(Constant.CHARACTER_SET), "AES");
 	        Cipher cipher = null;
 	        if(aesOffsets != null && !(aesOffsets.trim()).equals("")){
 	        	cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
 	        	if(aesOffsets.length() > 16){
 	        		byte[] bytes = parseHexStr2Byte(aesOffsets);
 	        		aesOffsets = new String(bytes, Constant.CHARACTER_SET);
 	        		System.out.println("转换后的偏移量：" + aesOffsets);
 	        	}
 	        	IvParameterSpec iv = new IvParameterSpec(aesOffsets.getBytes(Constant.CHARACTER_SET));
 		        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
 	        }else{
 	        	cipher = Cipher.getInstance("AES");
 	        	cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
 	        }
 	        
 	        byte[] decryptText = null;
 	        if(cipher != null){
 	        	decryptText = cipher.doFinal(plainText);
 	        }
 	        return decryptText;
          } catch(Exception e) {
              e.printStackTrace();
              return null;
          }
    }

    /**
     * 对AES算法加密的数据解密
     * @param cipherText  要解密的字节数组
     * @param key  密钥
     * @return 解密后的字节数组
     */
     public static byte[] decrypt(byte[] cipherText, String aeskey, String aesOffsets) throws Exception{
    		if(aeskey.length() > 16){
         		byte[] aesBytes = parseHexStr2Byte(aeskey);
         		aeskey = new String(aesBytes, Constant.CHARACTER_SET);
         		System.out.println("aeskey转换后的偏移量：" + aeskey);
         	}
             SecretKeySpec skeySpec = new SecretKeySpec(aeskey.getBytes(Constant.CHARACTER_SET), "AES");
             Cipher cipher = null;
             if(aesOffsets != null && !(aesOffsets.trim()).equals("")){
             	cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
             	if(aesOffsets.length() > 16){
 	        		byte[] bytes = parseHexStr2Byte(aesOffsets);
 	        		aesOffsets = new String(bytes, Constant.CHARACTER_SET);
 	        		System.out.println("转换后的偏移量：" + aesOffsets);
 	        	}
             	IvParameterSpec iv = new IvParameterSpec(aesOffsets.getBytes(Constant.CHARACTER_SET));
             	cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
             }else{
             	cipher = Cipher.getInstance("AES");
             	cipher.init(Cipher.DECRYPT_MODE, skeySpec);
             }
             byte[] plainText = null;
             if(cipher != null){
             	plainText = cipher.doFinal(cipherText);
             }
             return plainText;
     }
     
     /**
      * 对AES算法加密的数据解密,先将字节数组转为16进制，然后解密
      * @param cipherText  要解密的字节数组
      * @param key  密钥
      * @return 解密后的字节数组
      */
      public static byte [] decryptHex(String cipherText, byte [] key) {
         try{
             SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
             Cipher cipher = Cipher.getInstance("AES");
             cipher.init(Cipher.DECRYPT_MODE, skeySpec);
             byte[] plainText = cipher.doFinal(parseHexStr2Byte(cipherText));
             return plainText;
          } catch(Exception e) {
              e.printStackTrace();
              return null;
          }
      }
     
     /**
      * 二进制转换为16进制 
      */
     public static String parseByte2HexStr(byte buf[]) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < buf.length; i++) {
			String hex = Integer.toHexString(buf[i] & 0xFF);
			if (hex.length() == 1) {
				hex = '0' + hex;
			}
			sb.append(hex.toUpperCase());
		}
		return sb.toString();
     }
     
    /**
     * 将16进制转换为二进制
   　　	 */
     public static byte[] parseHexStr2Byte(String hexStr) {
    	if (hexStr.length() < 1)
    		return null;
    	byte[] result = new byte[hexStr.length()/2];
    	for (int i = 0;i< hexStr.length()/2; i++) {
    		int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);
    		int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);
    		result[i] = (byte) (high * 16 + low);
    	}
    	return result;
     }
	
     /**
      * zip 压缩 
      */
    public static byte[] compress(String str){
      if(str == null){
    	  return null;
      } 
      byte[] compressed;
      ByteArrayOutputStream out = null;
      ZipOutputStream zout = null;
       
      try {
        out = new ByteArrayOutputStream();
        zout = new ZipOutputStream(out);
        zout.putNextEntry(new ZipEntry("0"));
        zout.write(str.getBytes());
        zout.closeEntry();
        compressed = out.toByteArray();
      }
      catch(IOException e){
        compressed = null;
      }
      finally{
        if(zout != null) {
        	try{
        		zout.close();
        	}catch(IOException e){}
        }
      }
      if(out != null) {
    	 try {
    		 out.close();
         }catch(IOException e){}
      }
      	return compressed;
     }
    
    /**
     * zip 压缩 ，返回字符串
     */
   public static String compressToString(String str){
     if(str == null){
   	  return null;
     } 
     byte[] compressed;
     ByteArrayOutputStream out = null;
     ZipOutputStream zout = null;
     String zipString = "";
     try {
       out = new ByteArrayOutputStream();
       zout = new ZipOutputStream(out);
       zout.putNextEntry(new ZipEntry("0"));
       zout.write(str.getBytes("GBK"));
       zout.closeEntry();
       compressed = out.toByteArray();
       zipString = new sun.misc.BASE64Encoder().encodeBuffer(compressed);
     }
     catch(IOException e){
       compressed = null;
     }
     finally{
       if(zout != null) {
       	try{
       		zout.close();
       	}catch(IOException e){}
       }
     }
     if(out != null) {
   	 try {
   		 out.close();
        }catch(IOException e){}
     }
     	return zipString;
    }
     
   
   public static byte[] compressToBytes(byte[] str){
	     if(str == null){
	   	  return null;
	     } 
	     byte[] compressed;
	     ByteArrayOutputStream out = null;
	     ZipOutputStream zout = null;
	     try {
	       out = new ByteArrayOutputStream();
	       zout = new ZipOutputStream(out);
	       zout.putNextEntry(new ZipEntry("0"));
	       zout.write(str);
	       zout.closeEntry();
	       compressed = out.toByteArray();
	      
	     }
	     catch(IOException e){
	       compressed = null;
	     }
	     finally{
	       if(zout != null) {
	       	try{
	       		zout.close();
	       	}catch(IOException e){}
	       }
	     }
	     if(out != null) {
	   	 try {
	   		 out.close();
	        }catch(IOException e){}
	     }
	     	return compressed;
	    }
   
   public static byte[] compressToFileBytes(String str){
	     if(str == null){
	   	  return null;
	     } 
	    java.io.File file = new java.io.File("d:\\test\\command.xml");
	    FileWriter fw;
		try {
			fw = new FileWriter(file);
			fw.write(str);
			fw.close();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	   byte[]  compressed = null;
	   
	   File zipFile = new File("d:\\test\\command.zip");
		try {
			ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile));
			
			out.putNextEntry(new ZipEntry("command.xml"));
			FileInputStream in = new FileInputStream(file);
			int b;
			while((b = in.read()) != -1){
				out.write(b);
			}
			in.close();
			out.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	   compressed = getBytes("d:\\test\\command.zip");
	   
	   
	     	return compressed;
	    }



	

		/**
		 * 获得指定文件的byte数组
		 */
		public static byte[] getBytes(String filePath){
			byte[] buffer = null;
			try {
				File file = new File(filePath);
				if(file.exists()){
					FileInputStream fis = new FileInputStream(file);
					ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
					byte[] b = new byte[1000];
					int n;
					while ((n = fis.read(b)) != -1) {
						bos.write(b, 0, n);
					}
					fis.close();
					bos.close();
					buffer = bos.toByteArray();
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return buffer;
		}

		/**
		 * 根据byte数组，生成文件
		 */
		public static void getFile(byte[] bfile, String filePath,String fileName) {
			BufferedOutputStream bos = null;
			FileOutputStream fos = null;
			File file = null;
			try {
				File dir = new File(filePath);
				if(!dir.exists()&&dir.isDirectory()){//判断文件目录是否存在
					dir.mkdirs();
				}
				file = new File(filePath+"\\"+fileName);
				fos = new FileOutputStream(file);
				bos = new BufferedOutputStream(fos);
				bos.write(bfile);
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (bos != null) {
					try {
						bos.close();
					} catch (IOException e1) {
						e1.printStackTrace();
					}
				}
				if (fos != null) {
					try {
						fos.close();
					} catch (IOException e1) {
						e1.printStackTrace();
					}
				}
			}
		}
	
     /**
      * zip 解压缩 
      */
     public static String decompress(byte[] compressed) {
    	if(compressed == null){
    	   return null;
     	}
	     ByteArrayOutputStream out = null;
	     ByteArrayInputStream in = null;
	     ZipInputStream zin = null;
	     String decompressed;
	     try {
		     out = new ByteArrayOutputStream();
		     in = new ByteArrayInputStream(compressed);
		     zin = new ZipInputStream(in);
		     ZipEntry entry = zin.getNextEntry();
		     byte[] buffer = new byte[1024];
		     int offset = -1;
		     while((offset = zin.read(buffer)) != -1) {
		     out.write(buffer, 0, offset);
		     }
		     decompressed = out.toString();
	     } catch (IOException e) {
	    	 e.printStackTrace();
	    	 decompressed = null;
	     } finally {
	    	 if(zin != null) {
	    		 try {zin.close();} catch(IOException e) {}
		     }
		     if(in != null) {
		    	 try {in.close();} catch(IOException e) {}
		     }
		     if(out != null) {
		    	 try {out.close();} catch(IOException e) {}
		     }
	     }
	      
	     return decompressed;
     }
     
     /**
      * zip 解压缩 ,参数数字符串
      */
     public static String decompress(String compressedString) {
    	if(compressedString == null){
    	   return null;
     	}
	     ByteArrayOutputStream out = null;
	     ByteArrayInputStream in = null;
	     ZipInputStream zin = null;
	     byte[] compressed = null;
	     String decompressed;
	     try {
	    	 compressed = new BASE64Decoder().decodeBuffer(compressedString);
		     out = new ByteArrayOutputStream();
		     in = new ByteArrayInputStream(compressed);
		     zin = new ZipInputStream(in);
		     ZipEntry entry = zin.getNextEntry();
		     byte[] buffer = new byte[1024];
		     int offset = -1;
		     while((offset = zin.read(buffer)) != -1) {
		     out.write(buffer, 0, offset);
		     }
		     decompressed = out.toString();
	     } catch (IOException e) {
	    	 decompressed = null;
	     } finally {
	    	 if(zin != null) {
	    		 try {zin.close();} catch(IOException e) {}
		     }
		     if(in != null) {
		    	 try {in.close();} catch(IOException e) {}
		     }
		     if(out != null) {
		    	 try {out.close();} catch(IOException e) {}
		     }
	     }
	      
	     return decompressed;
     }
     
	public static byte[] getByteByBaseString(String str, String charSet) {
		byte[] bArray = null;
		try {
			bArray = str.getBytes(charSet);
			if (Base64.isArrayByteBase64(bArray)) {
				bArray = Base64.decodeBase64(bArray);
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return bArray;
	}
	
	//字符串转换为date
	public static Date stringToDate(String dateStr, String formatStr){
		DateFormat sdf=new SimpleDateFormat(formatStr);
		Date date=null;
		try {
			date = sdf.parse(dateStr);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return date;
	}
	
	//字符串转换为date
		public static Date stringToDate(String dateStr){
			DateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date date=null;
			try {
				date = sdf.parse(dateStr);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			return date;
		}
	
	public static String getStringByBaseString(String str) {
		String res = new String(getByteByBaseString(str));
		return res;
	}
	
	public static String getStringByBaseString(String str, String charSet) {
		String res = new String(getByteByBaseString(str, charSet));
		return res;
	}
	
	//生成n个字节的随机字符串
	public static String randomString(int length) {
		Random randGen = null;
		char[] numbersAndLetters = null;
         if (length < 1) {
             return null;
         }
         if (randGen == null) {
                randGen = new Random();
                numbersAndLetters = ("0123456789abcdefghijklmnopqrstuvwxyz" +
                   "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray();
                  //numbersAndLetters = ("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray();
                 }
         char [] randBuffer = new char[length];
         for (int i=0; i<randBuffer.length; i++) {
             randBuffer[i] = numbersAndLetters[randGen.nextInt(71)];
          //randBuffer[i] = numbersAndLetters[randGen.nextInt(35)];
         }
         return new String(randBuffer);
	}
	
	/**
	 * 生成随机字符串 （纯数字）
	 */
	public static String randomInt(int length) {
		Random randGen = null;
		char[] numbersAndLetters = null;
		if (length < 1) {
			return null;
		}
		if (randGen == null) {
			randGen = new Random();
			numbersAndLetters = ("0123456789").toCharArray();
			//numbersAndLetters = ("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray();
		}
		char [] randBuffer = new char[length];
		for (int i=0; i<randBuffer.length; i++) {
			randBuffer[i] = numbersAndLetters[randGen.nextInt(32)];
			//randBuffer[i] = numbersAndLetters[randGen.nextInt(35)];
		}
		return new String(randBuffer);
	}

	
	public static boolean isNull(String str){
		if(str == null){
			return true;
		}else if("".equals(str.trim())){
			return true;
		}
		
		return false;
	}
	
	public static boolean isNotNull(String str){
		return !isNull(str);
	}
	
	
	public static void main(String[] args) {
		String s = "1234567890123456123456789098765432234590987654324567890987654";
		
//		try {
//			byte[]  abytes = s.getBytes("UTF-8");
//			byte[]  aesbytes = aes(abytes, "4C4A5259525059463237343636393434", "565A4156554641453538363937393839");
//			byte[]  aesbytes = aes(abytes, "XZTNJHKP26452383", "PXRLSNNF98283378");
//			System.out.println(new String(aesbytes));
//			byte[]  bbytes = aes(aesbytes, "XZTNJHKP26452383", "PXRLSNNF98283378");
//			
//			System.out.println(new String(abytes,"UTF-8"));
//			System.out.println(new String(bbytes,"UTF-8"));
//			
//			String r = getBaseByByte(aesbytes);
//			System.out.println(r);
//			
//			byte[] dataArray = StringUtil.getByteByBaseString(r);
//			byte[] decrypt = StringUtil.decrypt(dataArray , "XZTNJHKP26452383", "PXRLSNNF98283378");
//			String aa = new String(decrypt,"UTF-8");
//			System.out.println(aa);
//			byte[] bytes = parseHexStr2Byte("565A4156554641453538363937393839");
//			String syr = new String(bytes);
//			System.out.println(syr);
//		} catch (UnsupportedEncodingException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		System.out.println(getIp("https://180.96.19.198/manage/interface/soap/commandack.php?wsdl"));
		
	}
	
	public static String getIp(String path){
		String newIp = "";
		//验证管局端IP地址
		if(path == null || !path.equals("")){
			path = path.toLowerCase();
			int start = path.indexOf("://");
			if(start != -1){
				path = path.substring(start + "://".length());
				if(path.indexOf(":") != -1){
					newIp = path.substring(0,path.indexOf(":"));
				}else if(path.indexOf("/") != -1){
					newIp = path.substring(0,path.indexOf("/"));
				}
			}
		}
		
		if(newIp.equals("localhost")){
			newIp = "127.0.0.1";
		}
		
		return newIp;
	}
}
